package com.lw.leetcode.linked.b;

import com.lw.leetcode.linked.ListNode;

/**
 * 面试题 02.05. 链表求和
 *
 * @Author liw
 * @Date 2021/5/14 13:38
 * @Version 1.0
 */
public class AddTwoNumbers {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode sum = new ListNode(0);
        ListNode f = sum;
        int flag = 0;
        ListNode item;
        while (l1 != null && l2 != null) {
            int value = l1.val + l2.val + flag;
            if (value > 9) {
                flag = 1;
                item = new ListNode(value - 10);
            } else {
                flag = 0;
                item = new ListNode(value);
            }
            sum.next = item;
            l1 = l1.next;
            l2 = l2.next;
            sum = item;
        }
        l1 = l1 == null ? l2 : l1;
        while (l1 != null) {
            int value = l1.val + flag;
            if (value > 9) {
                flag = 1;
                item = new ListNode(value - 10);
            } else {
                flag = 0;
                item = new ListNode(value);
            }
            sum.next = item;
            l1 = l1.next;
            sum = item;
        }
        if (flag == 1) {
            item = new ListNode(1);
            sum.next = item;
        }
        return f.next;
    }

}
